package com.phantom.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

import static com.phantom.nio.c1.ByteBufferUtil.debugAll;

@Slf4j
public class Server {

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for ( int j = 0; j < target.limit(); j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }

        source.compact();
    }

    public static void main(String[] args) throws IOException {

        // 创建Selector
        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        // 把channel注册到selector上
        // SelectionKey事件发生时，通过它可以知道事件和哪个channel的事件
        SelectionKey sscKey = ssc.register(selector, 0, null);
        // key只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("register key:{}", sscKey);

        ssc.bind(new InetSocketAddress(8880));
        while (true) {
            selector.select(); // select方法：没有事件线程阻塞，有事件线程恢复运行
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                log.debug("key: {}", key);
                if (key.isAcceptable()) { // 区分事件类型，如果是accept事件类型

                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    channel.configureBlocking(false); // SocketChannel必须工作在非阻塞模式

                    SocketChannel sc = channel.accept();

                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    SelectionKey scKey = sc.register(selector, 0, buffer); // 将一个buffer关联到selectionKey上
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("sc: {}", sc);

                } else if (key.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer readBuffer = (ByteBuffer) key.attachment();

                        int read = channel.read(readBuffer);
                        if (read == -1) { // 如果是正常断开，read的方法的返回值是-1
                            key.cancel();
                        } else {
                            split(readBuffer);
                            if (readBuffer.position() == readBuffer.limit()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(readBuffer.capacity() * 2);
                                readBuffer.flip();
                                newBuffer.put(readBuffer);
                                key.attach(newBuffer);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }

                // key.cancel();

            }

        }

    }
}
